# -*- coding: utf-8 -*-
import json
import re
from datetime import datetime, timedelta
import pandas as pd
import requests
from tqdm import tqdm

login_url = "http://e.arrowzl.cn/jterp/user/login"
token_url = "http://e.arrowzl.cn/jterp/user/loginByPhone"
token_1 = []
list_DDS = []
list_ID = []  # 空列表保存id
list_DDid = []  # 订单编号
list_SN = []  # 所有sn码，用来统计测试数量
list_SNs = []
list_Total = []  # 用来结算测试数量
timess = []


# 模拟登录发送验证码========================================================================================================
def get_yzm():
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0"}
    params = {"loginName": "冯教鸿", "password": "e10adc3949ba59abbe56e057f20f883e"}
    response = requests.post(login_url, json=params, headers=headers)
    data = response.json()
    if data.get("code") == 200:
        print("验证码发送成功,正在获取Token")
        token_1.append(data["data"]["token"])  # 提取token
        print(f'Token:\n{data["data"]["token"]}')
    else:
        print(f"验证码发送失败: {data.get('message', '未知错误')}")

    return token_1


# 登录系统，登录后才可以爬取不是直接用token就可以，是要后台保持登录状态============================================================
def log_in(m, tk):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "Referer": "http://e.arrowzl.cn/user/login",
        "Cookie": "x-hng=lang=zh-CN&domain=e.arrowzl.cn",  # 必须替换
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8",
    }

    params1 = {
        "code": str(m),
        "token": tk
    }
    response = requests.post(token_url, json=params1, headers=headers)
    data = response.json()
    print("正在登录.....")
    if data.get("code") == 200:
        print("登录成功")
    else:
        print(f"登录失败: {data.get('message', '未知错误')}")


# 获取ID和订单号
def run_id(a, b):
    while 1:
        Otime = input('输入查询的起始月日用空格隔开如(0606 6):\n').split()
        if len(Otime) > 2:
            print('输入有误,重输')
        else:
            if len(Otime) == 1:
                Otime.append("0")
            break
    OKtime = f"{str(datetime.now().year)}" + Otime[0]
    begintime = str(datetime.strptime(OKtime, "%Y%m%d").date())  # 开始日期
    endtime = str(datetime.strptime(OKtime, "%Y%m%d").date() + timedelta(days=int(Otime[1])))  # 结束日期
    timess.append(begintime)
    timess.append(endtime)
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "Referer": "http://e.arrowzl.cn/bill/checkassemble",
        "Cookie": "x-hng=lang=zh-CN&domain=e.arrowzl.cn",  # 必须替换
        "X-Requested-With": "XMLHttpRequest",
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8",
        "x-access-token": a
    }
    params = {
        "search": json.dumps({
            "type": "其它",
            "subType": "检测单",
            "roleType": "全部数据",
            "creator": b,
            "beginTime": begintime,  # 修改为要查询的日期
            "endTime": endtime}),
        "currentPage": 1,
        "pageSize": 20000
    }

    try:
        response = requests.Session().get(
            "http://e.arrowzl.cn/jterp/depotHead/list",
            headers=headers,
            params=params,
            timeout=10
        )
        if response.status_code == 200:  # 状态码为200说明访问成功
            data = response.text
            ids = re.findall(r'"id":\s*(\d+)', data)  # 提取id数值
            ddh = re.findall(r'"linkNumber":"([^"]*)"', data)  # 提取订单编号
            for i in range(len(ids)):
                list_ID.append(int(ids[i]))
            for i in range(len(ids)):
                list_DDid.append(str(ddh[i]))  # 保存订单编号进list

    except Exception as e:
        print("完整错误:", str(e))


def run_ok(a):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "Referer": "http://e.arrowzl.cn/bill/checkassemble",
        "Cookie": "x-hng=lang=zh-CN&domain=e.arrowzl.cn",  # 必须替换
        "X-Requested-With": "XMLHttpRequest",
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8",
        "x-access-token": a
    }
    params2 = {
        "headerId": "614229",
        "mpList": "",
        "linkType": "basic"
    }
    try:
        for i in tqdm(range(len(list_ID)), desc="查询进度", position=0, colour='blue'):
            response = requests.session().get(
                f"http://e.arrowzl.cn/jterp/depotItem/getDetailList?headerId={list_ID[i]}&mpList=&linkType=basic",
                headers=headers,
                params=params2,
                timeout=30
            )
            if response.status_code == 200:
                data = response.text
                sns = re.findall(r'"snListSure":\s*"([^"]*)"', data)
                for k in range(len(str(sns).split(","))):
                    list_Total.append(str(sns).split(",")[k])
                print(f'{len(list_Total)}')
    except Exception as e:
        print("完整错误:", str(e))
        exit()


def to_ricsv():
    print(f'查询时间:{timess[0]}测试数量:{len(list_Total)}')
    new_rows = {
        "日期": timess[0],
        "测数": len(list_Total),
        "结算": (len(list_Total) * 1.5)
    }
    new_df = pd.DataFrame(new_rows, index=[0])
    existing_df = pd.read_csv('_internal/日数.csv')
    existing_df = existing_df.dropna(axis=1, how='all')
    new_df = new_df.dropna(axis=1, how='all')
    updated_df = pd.concat([existing_df, new_df], ignore_index=True)
    updated_df.to_csv('_internal/日数.csv', index=False)
    print(f"{timess[1]}当天数量已统计到csv")


def main_(tok):
    get_who = int(input("Look Who?(1/2):"))
    if get_who == 1:
        get_creators = 13251
    elif get_who == 2:
        get_creators = 198
    else:
        print('输入有误')
        exit()
    while 1:
        run_id(tok, get_creators)
        run_ok(tok)
        to_ricsv()
        timess.clear()
        list_SNs.clear()
        list_DDS.clear()
        list_DDid.clear()
        list_ID.clear()
        list_Total.clear()


if __name__ == '__main__':
    token = input('Token(没有就回车):')
    if token == '':
        get_yzm()
        creators = ''
        yzm = input('手机验证码:\n')
        log_in(yzm, token_1[0])
        token = token_1[0]
        main_(token_1)
    else:
        main_(token)
